package com.blen.videolib;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.blen.videolib.edit.PictureUtils;
import com.blen.videolib.edit.VideoCutTimeActivity;
import com.blen.videolib.util.FFUtils;
import com.blen.videolib.util.FileUtils;
import com.blen.videolibs.R;


/**
 * Created by zhaoshuang on 17/2/21.
 * 视频编辑界面
 */

public class VideoEditActivity extends BaseActivity {

    private final int REQUEST_CUT_TIME = 10002;
    private final int REQUEST_CUT_SIZE = 10004;

    private MyVideoView vv_play;
    private TextView tvEdit;
    private TextView tvConfirm;

    private int dp20;
    private int dp25;

    private int currentColorPosition;
    private int windowHeight;
    private int windowWidth;
    private String path;

    private int dp100;
    private float videoSpeed = 1;
    private int videoWidth;
    private int videoHeight;
    private boolean isConfirm = false;
    MediaMetadataRetriever mMetadataRetriever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_edit);

        windowWidth = getWindowManager().getDefaultDisplay().getWidth();
        windowHeight = getWindowManager().getDefaultDisplay().getHeight();
        dp100 = (int) getResources().getDimension(R.dimen.dp100);
        mMetadataRetriever = new MediaMetadataRetriever();
        initUI();
        Intent intent = getIntent();
        path = intent.getStringExtra("path");
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMetadataRetriever.release();
    }

    private void initData() {
        try{
            int lenth = 0;
            mMetadataRetriever.setDataSource(path);
            lenth = Integer.parseInt(mMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
            checkLength(lenth);
            if(VideoSDK.isShowTime) {
                Toast.makeText(this, "文件长度:" + lenth, Toast.LENGTH_SHORT).show();
                Log.d("blensmile","video metaRetriever length is:"+lenth);
            }
        } catch ( RuntimeException e) {
            e.printStackTrace();
            Toast.makeText(this, "文件损坏或格式错误", Toast.LENGTH_SHORT).show();
            return;
        }

        vv_play.setVideoPath(path);
        vv_play.setOnErrorListener((mp,what,msg)->{
//            MediaPlayer mp, int what, int extra
            Log.d("blensmile",new StringBuilder()
                    .append("filepath: ").append(path)
                    .append(" \nwhat ").append(what)
                    .append(" msg ").append(msg)
                    .toString());
            return false;
        });
        vv_play.setOnPreparedListener(mp -> {
            vv_play.setLooping(true);
            vv_play.start();
//            int duration = vv_play.getDuration();
//            checkLength(duration);
            Log.d("blensmile","prepared called and duration is "+vv_play.getDuration());
        });
//        vv_play.setOnPlayStateListener(isPlaying -> {
//            if (isPlaying) {
//                videoWidth = vv_play.getVideoWidth();
//                videoHeight = vv_play.getVideoHeight();
//                float ra = videoWidth * 1f / videoHeight;
//                float widthF = videoWidth * 1f / 1280;//MediaRecorderBase.VIDEO_HEIGHT;
////                float heightF = videoHeight * 1f / MediaRecorderBase.VIDEO_WIDTH;
//                ViewGroup.LayoutParams layoutParams = vv_play.getLayoutParams();
//                layoutParams.width = (int) (windowWidth /** widthF*/);
//                layoutParams.height = (int) (layoutParams.width / ra);
////                vv_play.setLayoutParams(layoutParams);
//            }
//            Log.d("blensmile","isPlaying status : "+isPlaying);
//        });
    }

    private void checkLength(int duration){
        if(duration>VideoSDK.VIDEO_MAX_LENGTH+100){
            isConfirm = false;
            tvConfirm.setTextColor(0x5f3BAF20);
            tvEdit.setClickable(true);
            tvEdit.setVisibility(View.VISIBLE);
            SpannableStringBuilder b = new SpannableStringBuilder("只能分享").append(String.valueOf(VideoSDK.VIDEO_MAX_LENGTH/1000)).append("s内的视频, 点击去 ");
            int len = b.length();
            b.append("编辑");
            b.setSpan(new ForegroundColorSpan(Color.WHITE),0,len,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            b.setSpan(new AbsoluteSizeSpan((int)getResources().getDimension(R.dimen.dp14)),0,len,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvEdit.setText(b,TextView.BufferType.SPANNABLE);
            tvEdit.setGravity(Gravity.LEFT);
        }else if(duration<1){
            isConfirm = false;
            tvConfirm.setTextColor(0x5f3BAF20);
            tvEdit.setClickable(false);
            tvEdit.setTextColor(Color.WHITE);
            tvEdit.setVisibility(View.VISIBLE);
            tvEdit.setGravity(Gravity.LEFT);
            tvEdit.setText("暂时不支持特殊比例的视频");
        } else if(duration < VideoSDK.VIDEO_MIN_LENGTH){
            isConfirm = false;
            tvConfirm.setTextColor(0x5f3BAF20);
            tvEdit.setClickable(false);
            tvEdit.setTextColor(Color.WHITE);
            tvEdit.setVisibility(View.VISIBLE);
            tvEdit.setGravity(Gravity.LEFT);
            tvEdit.setText("视频时间太短了");
//            Toast.makeText(this,"视频时间有点短哦",Toast.LENGTH_SHORT).show();
        }  else {
            isConfirm = true;
            tvConfirm.setTextColor(0xff3BAF20);
            tvEdit.setVisibility(View.VISIBLE);
            tvEdit.setClickable(true);
            tvEdit.setText("编辑");
            tvEdit.setGravity(Gravity.RIGHT);
        }
    }

    private void initUI() {
        vv_play = findViewById(R.id.vvPlay);
        tvEdit = findViewById(R.id.tvEdit);
        tvConfirm = findViewById(R.id.tvConfirm);
        TextView tvCancel = findViewById(R.id.tvCancel);
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isConfirm) {
                    finishVideo();
                }
            }
        });
        tvCancel.setOnClickListener(v->onBackPressed());
        tvEdit.setOnClickListener(v->goEdit());
        vv_play.setOnClickListener(v->{
            View mask = findViewById(R.id.rlTitle);
            mask.setVisibility(mask.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
        });
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vv_play.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(vv_play != null && vv_play.isPaused()) {
            vv_play.start();
            Log.d("blensmile1","vvplay_start");
//            vv_play.reOpen();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String p=null;
            if(data!=null) {
                p = data.getStringExtra("videoPath");
                if(TextUtils.isEmpty(p)){
                    return;
                }
            }
            if(requestCode == REQUEST_CUT_TIME){
//                vv_play.setVideoPath(path);
//                vv_play.start();
                path = p;
                initData();
            }
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void finishVideo() {

        new AsyncTask<Void, Void, Intent>() {
            @Override
            protected void onPreExecute() {
                showProgress();
            }

            @Override
            protected Intent doInBackground(Void... params) {
                if(!TextUtils.isEmpty(path)){
                    String cover = getCover(path);
                    String tmp = path;
                    //压缩怎么能更高效...
                    if(false) {
                        String cache1 = VideoSDK.getVideoCache().append(System.currentTimeMillis()).append(".mp4").toString();
                        //压缩
                        // 获取bitrate, size
                        //
                        //是否需要压缩
                        String[] str = {
                                "ffmpeg",
                                "-i",
                                tmp,
                                "-c:v",
                                "libx264",
                                "-c:a",
                                "aac",
                                "-strict",
                                "experimental",
                                "-b:a",
                                "98k",
//                        "-c",
//                        "copy",
//                        "-copyts",
                                "-avoid_negative_ts",
                                "1",
                                cache1
                        };
                        if(FFUtils.run(str) == 0){
                            tmp = cache1;
                        }
                    }
                    String dest = VideoSDK.getVideoAlbum().append(System.currentTimeMillis()).append(".mp4").toString();
                    if( !tmp.contains(VideoSDK.getVideoAlbum()) && FileUtils.fileMove(tmp,dest)) {
                        if(!VideoSDK.isDebug) {
                            FileUtils.deleteDir(VideoSDK.getVideoCache().toString());
                        }
                    }else {
                        dest = tmp;
                    }
                    if(!TextUtils.isEmpty(cover)) {
                        Intent intent = new Intent();
                        intent.putExtra("videoPath", dest);
                        intent.putExtra("cover", cover);
                        return intent;
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Intent result) {
                hideProgress();
                if (result!=null) {
                    setResult(RESULT_OK,result);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "视频编辑失败", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    private String getCover(String mVideoPath){
        //TODO resultCode, 以及产生缩略图
        String des = VideoSDK.getVideoAlbum().append(System.currentTimeMillis()).append(".jpg").toString();
        boolean success = FFUtils.getThumbnail(mVideoPath, des,"0");
        if(!success){
            MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
            metadataRetriever.setDataSource(mVideoPath);
            Bitmap bitmapNew = metadataRetriever.getFrameAtTime();
            if (bitmapNew != null) {
                PictureUtils.saveImageToSDForEdit(bitmapNew,des);
                if (!bitmapNew.isRecycled()) {
                    bitmapNew.recycle();
                }
            }
            metadataRetriever.release();
        }
        return des;
    }

    private void goEdit(){
        Intent intent = new Intent(this, VideoCutTimeActivity.class);
        intent.putExtra("path", path);
        startActivityForResult(intent, REQUEST_CUT_TIME);
    }
}
